package com.aiyige.page.my.order.adapter;

import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.apiengine.ActionEngine;
import com.aiyige.base.eventbus.EventOrderChanged;
import com.aiyige.model.OperationModel;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.User;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.request.BuyerOrderActionRequest;
import com.aiyige.model.request.OrderStatusEnum;
import com.aiyige.page.login.LoginPage;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.page.my.order.OrderActionUtils;
import com.aiyige.page.my.order.dialog.ConfirmInClassDialog;
import com.aiyige.page.my.order.model.KeyValue;
import com.aiyige.page.my.order.myOrder.SearchTypeMyOrderPage;
import com.aiyige.page.pay.model.OrderModel;
import com.aiyige.page.user.UserPage;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.MomentUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.LabelImageView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by zhuyakun on 2017/10/17.
 */

public class OrderListAdapter extends BaseQuickAdapter<OrderEntity, BaseViewHolder> {


    SearchValueCallback callback;

    public void setSearchValueCallback(SearchValueCallback callback) {
        this.callback = callback;
    }

    public interface SearchValueCallback {
        String getSearchValue();
    }

    public void OrderListAdapter(SearchValueCallback callback) {
        this.callback = callback;
    }


    public boolean isHideTypeLayout() {
        return hideTypeLayout;
    }

    public void setHideTypeLayout(boolean hideTypeLayout) {
        this.hideTypeLayout = hideTypeLayout;
    }

    public boolean isHideContentLayout() {
        return hideContentLayout;
    }

    public void setHideContentLayout(boolean hideContentLayout) {
        this.hideContentLayout = hideContentLayout;
    }

    public boolean isHideOperationLayout(OrderEntity orderEntity) {
        return ListUtil.isEmpty(orderEntity.getOperationList());
    }

    public void setHideOperationLayout(boolean hideOperationLayout) {
        this.hideOperationLayout = hideOperationLayout;
    }

    boolean hideTypeLayout = false;

    boolean hideContentLayout = false;

    boolean hideOperationLayout = false;

    boolean isBuyer = true;

    public boolean isBuyer() {
        return isBuyer;
    }

    public void setBuyer(boolean buyer) {
        isBuyer = buyer;
    }

    public OrderListAdapter() {
        super(new LinkedList<OrderEntity>());
    }


//    @Override
//    protected void convert(BaseViewHolder helper, OrderEntity item) {
//
//        if (item.isShowTypeNameLayout()) {
//            ((OrderHasTitleHolder) helper).bindData(item);
//        } else {
//            ((MyHolder) helper).bindData(item);
//        }
//    }

    @Override
    protected void convert(BaseViewHolder helper, OrderEntity item) {
        ((OrderHolder) helper).bindData(item);
    }

//    @Override
//    protected int getDefItemViewType(int position) {
////        return mData.get(position).isShowTypeNameLayout() ? 0 : 1;
//        return mData.get(position).isShowTypeNameLayout();
//    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
//        BaseViewHolder baseViewHolder = viewType == 0 ? new OrderHasTitleHolder(getItemView(R.layout.item_order, parent)) :
//                new MyHolder(getItemView(R.layout.item_order_waste, parent));
        BaseViewHolder baseViewHolder = new OrderHolder(getItemView(R.layout.item_order, parent));
        return baseViewHolder;
    }

    @Override
    public void setNewData(@Nullable List<OrderEntity> data) {
        super.setNewData(data);
    }

    public class OrderHolder extends BaseViewHolder {
        @BindView(R.id.rl_type)
        View rlType;

        @BindView(R.id.tv_type_name)
        TextView tvTypeName;
        @BindView(R.id.ll_more)
        LinearLayout llMore;
        @BindView(R.id.iv_right)
        ImageView ivRight;
        @BindView(R.id.tv_more)
        TextView tvMore;
        @BindView(R.id.ll_containerLayout)
        LinearLayout llContent;

        @BindView(R.id.ll_count)
        LinearLayout llCount;



        @BindView(R.id.order_layout)
        View orderLayout;


        @BindView(R.id.iv_head)
        ImageView ivHead;
        @BindView(R.id.iv_seller_level)
        ImageView ivSellerLevel;
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_status)
        TextView tvStatus;
        @BindView(R.id.iv_cover)
        LabelImageView ivCover;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        //        @BindView(R.id.tv_tag)
//        TextView tvTag;
        @BindView(R.id.tv_price)
        TextView tvPrice;
        @BindView(R.id.tv_lineation_price)
        TextView tvLineationPrice;
        @BindView(R.id.tv_count)
        TextView tvCount;
        //        @BindView(R.id.tv_order_id)
//        TextView tvOrderId;
        @BindView(R.id.tv_content_count)
        TextView tvContentCount;
        @BindView(R.id.centerLayout)
        View llCenterLayout;

        @BindView(R.id.tv_order_time)
        TextView tvOrderTime;

//        @BindView(R.id.iv_more)
//        ImageView ivMore;

        @BindView(R.id.ll_city)
        LinearLayout llCity;
        @BindView(R.id.tv_city)
        TextView tvCity;
        @BindView(R.id.tv_date_info)
        TextView tvDateInfo;

        @BindView(R.id.tv_feedback)
        TextView tvFeedback;


        @BindView(R.id.operation_layout)
        View operationLayout;

        @BindView(R.id.ll_operation_list)
        LinearLayout llOperationList;

        OrderEntity record;

        OrderActionUtils itemDataUtils;

        public OrderHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            itemDataUtils = new OrderActionUtils();
        }


        public void bindData(final OrderEntity order) {
            record = order;
            record.setBuyer(isBuyer());
            if (record.getStatus() == OrderStatusEnum.STATUS_3_WAITING_SHIP.getStatus()) {
                tvTypeName.setText(mContext.getString(R.string.waiting_service_page));
            }
            else{
                tvTypeName.setText(record.getStatusString());
            }

            if (TextUtils.isEmpty(record.getOrderId())) {
                orderLayout.setVisibility(View.GONE);
                tvMore.setText(mContext.getString(R.string.no_search_result));
                ivRight.setVisibility(View.GONE);
            } else {
                rlType.setVisibility(record.isShowTypeNameLayout() ? View.VISIBLE : View.GONE);
                llContent.setVisibility(View.VISIBLE);
                ivRight.setVisibility(View.VISIBLE);
                if (record.isHasMore()) {
                    tvMore.setText(mContext.getString(R.string.more));
                    llMore.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SearchTypeMyOrderPage.start(record.getStatus(), callback.getSearchValue());
                        }
                    });
                } else {
                    llMore.setVisibility(View.INVISIBLE);
                }
                if (isHideTypeLayout()) {
                    rlType.setVisibility(View.GONE);
                }
                if (isHideContentLayout()) {
                    orderLayout.setVisibility(View.GONE);
                }
                if (isHideOperationLayout(order)) {
                    operationLayout.setVisibility(View.GONE);
                } else {
                    operationLayout.setVisibility(View.VISIBLE);
                }
                GlideUtil.with(itemView.getContext()).small().loadAvatar(isBuyer()?order.getSellerAvatar():order.getBuyerAvatar()).into(ivHead);
                ivSellerLevel.setVisibility((isBuyer()?order.getSellerLevel():order.getBuyerLevel()) > 0 ? View.VISIBLE : View.INVISIBLE);
                tvName.setText(isBuyer()?order.getSellerName():order.getBuyerName());
                tvStatus.setText(order.getStatusString());
                GlideUtil.with(itemView.getContext()).big().loadCover(order.getCover().get(0)).into(ivCover.getImageView());
                Spanned result;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                    result = Html.fromHtml(order.getTitle(), Html.FROM_HTML_MODE_LEGACY);
                } else {
                    result = Html.fromHtml(order.getTitle());
                }
                tvTitle.setText(order.isSearch()?result:order.getTitle());
                ivCover.setLabel(order.getTypeName());
                llCount.setVisibility(View.VISIBLE);
                tvCount.setText(order.getNum()+"");
                if (!TextUtils.isEmpty(order.getGoodsType())) {
                    itemDataUtils.fillViews(order.getGoodsType(), llCity, tvCity, order.getCityName(), order.getMoreBackupJson(), tvContentCount, tvDateInfo, order.getVideoStages());
                }
                tvFeedback.setText(order.getRefundStatusString());
                tvPrice.setText("￥"+StringUtils.priceFormat(order.getAmount()));
                tvLineationPrice.setVisibility(View.GONE);
//                tvLineationPrice.setText("￥"+StringUtils.priceFormat(order.getLineationAmount()));
//                tvLineationPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
                tvOrderTime.setText(mContext.getString(R.string.order_time_value, TimeUtils.dateToYYYYMMDDHHSS(order.getCreateTime())));
                llCenterLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ARouter.getInstance().build(ARouterConfig.OrderDetailPage).withBoolean("isBuyer", isBuyer()).withString("orderId", order.getOrderId()).navigation();

                    }
                });
                tvName.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v) {
                        UserPage.start(isBuyer()?order.getSellerId():order.getBuyerUserId());
                    }
                });
                ivHead.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v) {
                        UserPage.start(isBuyer()?order.getSellerId():order.getBuyerUserId());
                    }
                });

                // 操作
                fillOperationLayout(llOperationList, order, order.getOperationList());

            }
        }
    }

    // 立即支付
    private void doOrderPayNow(OrderEntity orderEntity) {
        if (!LoginManager.isLogin()) {
            LoginPage.start();
            return;
        }
        if (orderEntity == null) {
            return;
        }
        User user = AccountUtil.getCurrentUser();
        if (user != null && TextUtils.isEmpty(user.getMobile())) {
            ARouter.getInstance().build(ARouterConfig.BindingPhonePage).navigation();
            return;
        }
        try {
            OrderModel orderModel = OrderModel.newBuilder()
                    .orderId(orderEntity.getOrderId())
                    .sellerId(orderEntity.getSellerId())
                    .goodsId(orderEntity.getMomentId())
                    .coverUrl(ListUtil.isEmpty(orderEntity.getCover()) ? "" : orderEntity.getCover().get(0))
                    .sellerName(orderEntity.getSellerName())
                    .sellerAvatar(orderEntity.getSellerAvatar())
                    .singlePrice(orderEntity.getAmount())
                    .totalPayPrice(orderEntity.getAmount())
                    .totalPrice(orderEntity.getAmount())
                    .buyNum(orderEntity.getNum())
                    .subject(orderEntity.getGoodsType())
                    .subjectIndex(MomentUtil.convertSubjectToSubjectIndex(orderEntity.getGoodsType()))
                    .source(orderEntity.getSource())
                    .sourceUrl(orderEntity.getSourceUrl())
                    .title(orderEntity.getTitle())
                    .build();
            ARouter.getInstance()
                    .build(ARouterConfig.ConfirmPayPage)
                    .withParcelable("orderModel", orderModel)
                    .navigation();
        } catch (Exception e) {

        }
    }


    // 取消订单
    private void doOrderCancel(final OrderEntity orderEntity) {
        showDialog();
        BuyerOrderActionRequest.newBuilder().id(orderEntity.getOrderId() + "").action_engine(ActionEngine.CANCEL_BY_BUYER).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                dismissDialog();
                try {
                    if (!response.isSuccessful()) {
                        throw new Exception(mContext.getString(R.string.request_failed));
                    } else {
                        String json = response.body().string();
                        if (!TextUtils.isEmpty(json)) {
                            Order order = JsonUtil.toObject(json, Order.class);
                            OrderEntity orderEntity1 = new OrderEntity(order);
                            if (orderEntity1 != null) {
                                notifyItemDataSetChanged(orderEntity1);
                            }
                            EventBus.getDefault().post(EventOrderChanged.newBuilder().orderEntity(orderEntity1).build());
                            ToastX.show(mContext.getString(R.string.order_cancelled));
                        }
                    }
                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                dismissDialog();
                if (!TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    private void notifyItemDataSetChanged(OrderEntity orderEntity) {
        if (ListUtil.isEmpty(getData())) {
            return;
        }
        for (int i = 0; i < getData().size(); i++) {
            if (orderEntity.getOrderId().equals(getData().get(i).getOrderId())) {
                getData().remove(i);
                getData().add(i, orderEntity);
                break;
            }
        }
        notifyDataSetChanged();


    }

    private void showDialog() {
        ((BaseActivity) mContext).showLoading();
    }

    private void dismissDialog() {
        ((BaseActivity) mContext).hideLoading();
    }


    private void cancelOrderDialog(final OrderEntity orderEntity) {
        new AlertDialog.Builder(mContext).setTitle(R.string.alert_cancel_order)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        doOrderCancel(orderEntity);
                    }
                })
                .setNegativeButton(R.string.back, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    private void deleteOrderDialog(final OrderEntity orderEntity) {
        new AlertDialog.Builder(mContext).setTitle(R.string.alert_delete_order)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        doOrderDelete(orderEntity);
                    }
                })
                .setNegativeButton(R.string.back, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    // 重新购买
    private void doOrderReBuy(OrderEntity orderEntity) {
        if (!LoginManager.isLogin()) {
            LoginPage.start();
            return;
        }
        if (orderEntity == null) {
            return;
        }
        User user = AccountUtil.getCurrentUser();
        if (user != null && TextUtils.isEmpty(user.getMobile())) {
            ARouter.getInstance().build(ARouterConfig.BindingPhonePage).navigation();
            return;
        }
        try {
            OrderModel orderModel = OrderModel.newBuilder()
                    .orderId(orderEntity.getOrderId())
                    .sellerId(orderEntity.getSellerId())
                    .goodsId(orderEntity.getMomentId())
                    .coverUrl(ListUtil.isEmpty(orderEntity.getCover()) ? "" : orderEntity.getCover().get(0))
                    .sellerName(orderEntity.getSellerName())
                    .sellerAvatar(orderEntity.getSellerAvatar())
                    .singlePrice(orderEntity.getAmount())
                    .totalPayPrice(orderEntity.getAmount())
                    .totalPrice(orderEntity.getAmount())
                    .buyNum(orderEntity.getNum())
                    .subject(orderEntity.getGoodsType())
                    .subjectIndex(MomentUtil.convertSubjectToSubjectIndex(orderEntity.getGoodsType()))
                    .source(orderEntity.getSource())
                    .sourceUrl(orderEntity.getSourceUrl())
                    .title(orderEntity.getTitle())
                    .build();
            ARouter.getInstance()
                    .build(ARouterConfig.ConfirmPayPage)
                    .withParcelable("orderModel", orderModel)
                    .navigation();
        } catch (Exception e) {

        }
    }

    // 删除订单
    private void doOrderDelete(final OrderEntity orderEntity) {
        showDialog();
        BuyerOrderActionRequest.newBuilder().id(orderEntity.getOrderId() + "").action_engine(ActionEngine.HIDEBY_BUYER).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                dismissDialog();
                try {
                    if (!response.isSuccessful()) {
                        throw new Exception(mContext.getString(R.string.request_failed));
                    } else {
                        orderEntity.setStatus(OrderStatusEnum.STATUS_2_CANCEL.getStatus());
                        List<OrderEntity> list = getData();
                        for (int i = 0; i < list.size(); i++) {
                            if (orderEntity.getOrderId() == list.get(i).getOrderId()) {
                                list.remove(i);
                                break;
                            }
                        }
                        notifyDataSetChanged();
                        ToastX.show(mContext.getString(R.string.order_deleted));
                        orderEntity.setStatus(OrderEntity.STATUS_DELETED);
                        EventBus.getDefault().post(EventOrderChanged.newBuilder().orderEntity(orderEntity).build());
                    }
                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                dismissDialog();
                if (!TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }


    private List<KeyValue> getNoPayMoreList() {
        List<KeyValue> list = new ArrayList<>();
        list.add(new KeyValue(0, mContext.getResources().getString(R.string.pay_now)));
        list.add(new KeyValue(1, mContext.getResources().getString(R.string.order_cancel)));
        return list;
    }


    private void fillOperationLayout(LinearLayout linearLayout, final OrderEntity orderEntity, List<OperationModel> list) {
        if (!ListUtil.isEmpty(orderEntity.getOperationList())) {
            linearLayout.removeAllViews();
            for (final OperationModel operation : list) {
                View item = LayoutInflater.from(mContext).inflate(R.layout.item_operation_button, null);
                TextView itemOperation = (TextView) item.findViewById(R.id.tv_operation);
                itemOperation.setText(operation.getOperationValue());
                itemOperation.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (operation.getOperationKey().equals(OperationModel.kCancelOrder)) {//取消订单
                            cancelOrderDialog(orderEntity);
                        } else if (operation.getOperationKey().equals(OperationModel.kImmediatePay)) {//立即支付
                            doOrderReBuy(orderEntity);
                        } else if (operation.getOperationKey().equals(OperationModel.kApplyRefund)) {//申请退款
                            ARouter.getInstance().build(ARouterConfig.RefundApplyForPage).withParcelable("orderEntity", orderEntity).navigation();
                        } else if (operation.getOperationKey().equals(OperationModel.kConfirmClassed)) {//确认上课
                            ConfirmInClassDialog.newInstance(orderEntity.getOrderId()).setListener(new ConfirmInClassDialog.Listener() {
                                @Override
                                public void onConfirmClassed(OrderEntity orderEntity) {
                                    notifyItemDataSetChanged(orderEntity);
                                }
                            }).show(((BaseActivity) mContext).getSupportFragmentManager(), "");
                        } else if (operation.getOperationKey().equals(OperationModel.kRefundDetail)) {//订单详情
                            ARouter.getInstance().build(ARouterConfig.RefundApplyDetailPage).withString("refundId", orderEntity.getRefundId()).withBoolean("isBuyer",isBuyer).navigation();
                        } else if (operation.getOperationKey().equals(OperationModel.kDeleteOrder)) {//删除订单
                            deleteOrderDialog(orderEntity);
                        }// 卖家处理退款申请
                        else if (operation.getOperationKey().equals(OperationModel.kProcessRefund)) {
                            ARouter.getInstance().build(ARouterConfig.RefundDisposePage).withParcelable("orderEntity", orderEntity).navigation();
                        }
                    }
                });
                linearLayout.addView(item);
            }
            linearLayout.setVisibility(View.VISIBLE);
        } else {
            linearLayout.setVisibility(View.GONE);
        }

    }


    private List<KeyValue> getCanceledMoreList() {
        List<KeyValue> list = new ArrayList<>();
//        list.add(new KeyValue(0, mContext.getResources().getString(R.string.repay)));
        list.add(new KeyValue(1, mContext.getResources().getString(R.string.delete_order)));
        return list;
    }

}
